package com.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.security.entity.Member;
import com.security.mapper.MemberMapper;
import com.security.tools.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
@SpringBootTest
public class InterfaceOptimizeApplicationTests2 {

    /**
     * 缓存10天
     */
    private static final int EXPECTED = 10 * 24 * 60 * 60;

    /**
     * 缓存key前缀
     */
    private static final String MEMBER_CACHE_PRE = "member_";
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private MemberMapper memberMapper;

    @Test
    void pushInRedis() {
        Stopwatch watch = Stopwatch.createStarted();
        List<Integer> ids = IntStream.range(1, 30000).boxed().collect(Collectors.toList());
        List<Member> members = memberMapper.selectBatchIds(ids);
        members.stream().forEach(member -> redisUtil.setObject(MEMBER_CACHE_PRE.concat(member.getAccountNumber()), member, EXPECTED));
        long time = watch.elapsed(TimeUnit.MILLISECONDS);
        //代码执行时长：8100
        log.info("代码执行时长：" + time);
    }

    @Test
    void contextLoads() {
        Stopwatch watch1 = Stopwatch.createStarted();
        List<Integer> ids = IntStream.range(1, 30000).boxed().collect(Collectors.toList());
        List<Member> members = memberMapper.selectBatchIds(ids);
        List<String> accounts = members.stream().map(Member::getAccountNumber).collect(Collectors.toList());
        log.info("代码执行时长1：" + watch1.elapsed(TimeUnit.MILLISECONDS));
        Stopwatch watch2 = Stopwatch.createStarted();
        List<Member> list= Lists.newArrayList();
        accounts.stream().filter(Objects::nonNull).forEach(account->{
            Object object = redisUtil.getObject(MEMBER_CACHE_PRE.concat(account));
            if(Objects.isNull(object)){
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("account_number",account);
                Member member = memberMapper.selectOne(queryWrapper);
                System.out.println("走数据库查询");
                if(Objects.nonNull(member)){
                    redisUtil.setObject(MEMBER_CACHE_PRE.concat(member.getAccountNumber()), member, EXPECTED);
                    list.add(member);
                }
            }else{
                list.add((Member) object);
            }
        });
        //代码执行时长2：3187,list大小：28261
        //代码执行时长2：3080,list大小：28261
        log.info("代码执行时长2：{},list大小：{}" , watch2.elapsed(TimeUnit.MILLISECONDS),list.size());
    }

}
